package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("1002")
public class TrackStrategy implements ItemTypeStrategy {
    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //添加购买声音 如果只有小程序--单线程的。不会出现脏数据，如果有多个平台；pc,h5
        //通过用户id、专辑id 查询到已购买的集合；判断已购买的集合中是否包含trackId; 如果包含，不能执行插入。使用continue 跳出当前循环 并可能退还对应的金额
        //1、通过用户支付声音userPaidTrackMapper接口 通过用户id 订单号 判断该订单是否有订单支付count记录
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(wrapper);
        //有订单数count 直接return结束
        if (count > 0) {
            return;
        }
        //从形参vo中拿取订单的声音id list
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        //通过声音远程接口，根据声音id 查询声音信息 获取专辑id 赋值结果集
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfoById(itemIdList.get(0));
        Asserts.notNull(trackInfoResult, "声音信息不存在");
        TrackInfo trackInfo = trackInfoResult.getData();
        Asserts.notNull(trackInfo, "声音信息不存在");
        //遍历订单itemIdList  声音idList 创建UserPaidTrack对象 依次保存到UserPaidTrack表
        for (Long itemId : itemIdList) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(itemId);
            userPaidTrackMapper.insert(userPaidTrack);
        }
    }
}
